/**
 * Created by Administrator on 2017-06-12.
 */
var index = {
    init : function(){
    	this.mask = [0];
    	this.subScribeTime;
    	this.base64 = new Base64();
        this.sliderH();         //计算左边栏高度
        this.treeTabInit = this.treeTab();          //初始化树切换函数
        this.detailInit = this.detail();            //初始化详情页tab切换
        this.detailGridInit = this.detailGrid();
        this.bind();
        this.ztreeCreat();
        this.initTableData();                       //查询结果表初始化
        this.initSubscribeTable();                  //订阅表初始化
        this.carTree=null;                          // 树对象
        this.vehicleArrayTimer=null;               //订阅定时器 
        this.arrayObj = new Array();
        mapTool.init();
        AMap.plugin(['AMap.ToolBar'],function(){
       	 mapTool.map.addControl(new AMap.ToolBar());
        });
        mapTool.drag({
        	h : 42,
        	callback : function(height){
        		index.myGrid.enableAutoHeight(true,height,true);
        		index.reloadGridData();
        	}
        });
        this.terminalMap = new HashMap();
        this.vehicleMap = new HashMap();
        this.vehicleID=null;
        this.GlobelVehicle = new HashMap();
        this.onlineVehicleStr = null;
        this.trafficLayer=null;
        this.uuidCache=new HashMap();
        this.allNum = new Array();
    	this.runNum = new Array();
      	this.stopNum = new Array();
      	this.droppedNum = new Array();
      	this.vehicleStatus = [0,0,0,0];
      	this.GlobelSubScribeVehicle=new HashMap();		//	缓存订阅信息
      	this.GlobelSubScribeCommno=new HashMap();
      	this.subScriberTime=this.timer();
      	this.ImgUrlCache = new HashMap();
      	this.vehicleNoColor = new HashMap();
      	this.vehicleColor = new HashMap();
      	this.myGrid;
      	this.GlobalGpsCache=new HashMap();
      	this.GlobalVehilceNo=new HashMap();
      	this.GlobalAddress = new HashMap();
      	this.GlobalGridField = ['vehicleId','vehicleId','vehicleChinaColor','accChainaStatus','carStatus','validS','gpsTimeS','gpsSpeedF','pulseSpeedF','gpsMileage','address'];
      	this.GlobalMarkerMatterCache = [];
      	this.isopenWin=false;
      	this.infoWindow=null;
      	this.MARKID=null;
      	
      	this.jsonArr="";
      	this.showCar=false;
    	this.selectRowData="";//储存选中行数据
      	this.GlobaljsonData="";
    },
    
    /**
     * 计算各div高度的高度
     * */
    sliderH : function(){
        var winH = $(window).height();
        var sliderH = winH - 76;
        $('.content').css({
            'height' : sliderH + 'px'
        });

        var treeDivH = sliderH - 64;
        $('#carTreeList,.tree').height(treeDivH + 7);

        var mapH = sliderH - 230;
        $('#mymap').height(mapH);

        this.flexigridH = treeDivH- 22 -225;
        this.mapH = mapH;
    },

    /**
     * 树切换
     * */
    treeTab : function(){
        var index = 0;
        $('.tree-title-list').click(function(){
            index = $(this).index();
            func(index);
        });
        var placeholderArr = ['查询业户信息','查询车辆信息'];
        var func = function(index){
        	$('.tree-title-list').find('a').removeClass('active');
        	$('.tree-title-list').eq(index).find('a').addClass('active');
            $('.tree-cont-list').hide().eq(index).show();
            $('.tree-title-line').css({
                left:50 * index + '%'
            });
            $('.search-input').attr('placeholder',placeholderArr[index]);
            if(index == 1){
            	$('.car-details').show();
            }else{
            	$('.car-details').hide();
            }
        };
        var searchFunc = function(eq){
            index = eq;
            func(index);
        };
        return {
            searchFunc : searchFunc
        };
    },

    /**
     * 详情内容tab切换
     * */
    detail : function(){
    	var _this = this;
        var index = 0;
        var func = function(index){
            $('.car-details-title-list').removeClass('active').eq(index).addClass('active');
            $('.car-details-cont-list').removeClass('active').hide().eq(index).addClass('active').show();
        };
        $('.car-details-title ').on('click','.car-details-title-list',function(){
            index = $(this).index();
            func(index);
        });
        var clickCar= function(eq){
            index = eq;
            func(index);
            
        };
        return {
            clickCar : clickCar,
            index : function(){
                return index;
            }
        }
    },
    /**
     * 订阅tab切换
     * */
    detailGrid : function(){
    	var _this = this;
        var index = 0;
        var func = function(index){
            $('.car-staues-list').removeClass('active').eq(index).addClass('active');
        };
        $('.car-staues-ul').on('click','.car-staues-list',function(){
            index = $(this).index();
            func(index);
            _this.subScribe(_this.arrayObj.toString());
        });
        return {
            index : function(){
                return index;
            }
        }
    },
    /**
     * 查看大图
     * */
    /*lookBigImg : function(){
        $('.lager-img').show();
        $('#mask').show();
    },*/

    /**
     * 加载树
     * */
    ztreeCreat : function(){
    	var _this = this;
        var setting = {
            check : {
                enable : false,

                chkboxType : {
                    "Y" : "ps",
                    "N" : "ps"
                }
            },
            data : {
                key : {
                    name : "NAME"
                },
                simpleData : {
                    enable : true,
                    idKey : "ID",
                    pIdKey : "PID",
                    rootPId : 0
                }
            },
            callback : {
                onClick : index.zTreeOnClick,
                onExpand : index.zTreeOnExpand
            }
        };
        $.ajax({
			type : 'post',
			async : true,
			url : appCtx+"/gis/monitor/getVehicleTree.html",
			cache : true,
			dataType : "JSON",
			success : function(data){
				index.carTree=$.fn.zTree.init($("#carTreeList"), setting, data);
				global.maskHide(0,_this);
				var da = JSON.parse(JSON.stringify(data));
				_this.searchTreeInit = _this.searchTree(da);
				//index.getVehicleStatus(); 
			}
		});
        
    },
    
    /*
     * 定位树搜索
     * */
    searchTree: function(data){
    	//data = JSON.parse(JSON.stringify(data));
    	var _this = this;
        var setting = {
            check : {
                enable : false,

                chkboxType : {
                    "Y" : "ps",
                    "N" : "ps"
                }
            },
            data : {
                key : {
                    name : "NAME"
                },
                simpleData : {
                    enable : true,
                    idKey : "ID",
                    pIdKey : "PID",
                    rootPId : 0
                }
            },
            callback : {
                onClick : index.zTreeOnClick,
                onExpand : index.zTreeOnExpand
            }
        };
        var obj = {
        	level1: [],
        	level2: [],
        	level3: [],
        	level4: []
        };
        var dataObj = {};
        var len = data.length;
        for(var i=0;i<len;i++){
			var da = data[i];
			dataObj[da.ID] = da;
			if(typeof(da.LEVEL != 'number')){
				da.LEVEL = JSON.parse(da.LEVEL);
			}
			switch (da.LEVEL) {
				case 1:
					obj.level1.push(da);
					break;
				case 2:
					obj.level2.push(da);
					break;
				case 3:
					obj.level3.push(da);
					break;
				case 4:
					obj.level4.push(da);
					break;
			};
		}
    	var func = function(val){
    		var level4 = level(obj.level4,val);
    		var level3 = level(obj.level3,val);
    		var level2 = level(obj.level2,val);
    		var level1 = level(obj.level1,val);
    		//var parent = [];
    		var searchData = level4.concat(level3,level2,level1);
    		console.log(level4);
    		for(var i=0;i<4;i++){
    			var pidArrLength = pidArr.length;
    			for(var j=0;j<pidArrLength;j++){
    				if(dataObj[pidArr[j]]){
    					if(idArr.indexOf(dataObj[pidArr[j]].ID) == -1){
    						dataObj[pidArr[j]].open = true;
        					searchData.push(dataObj[pidArr[j]]);
        					idArr.push(dataObj[pidArr[j]].ID);
    					}
    					if(pidArr.indexOf(dataObj[pidArr[j]].PID) == -1){
    						pidArr.push(dataObj[pidArr[j]].PID);
    					}
    				}
    			}
    		}
    		/*console.log(searchData);
    		console.log(pidArr);*/
    		
    		
    		$('#carTreeList').hide();
    		$("#searchCarTree").show();
    		index.searchCarTree=$.fn.zTree.init($("#searchCarTree"), setting, searchData);
    		pidArr = [];
    		idArr = [];
    	};
    	
    	var pidArr = [];
    	var idArr = [];
    	var level = function(arr,val){
    		var newArr = [];
    		for(var i=0;i<arr.length;i++){
    			if(arr[i].NAME.indexOf(val) > -1){
    				arr[i].open = true
    				newArr.push(arr[i]);
    				idArr.push(arr[i].ID);
    				var Pid = arr[i].PID;
    				if(pidArr.indexOf(Pid) == -1){
    					pidArr.push(Pid);
    				}
    			}
    		}
    		return newArr;
    	};
    	
    	return {
    		search: func
    	};
    },
    
    /**
     * 车辆id与通信号的缓存
     * @param data
     */
    initTerminalMap : function(data){
    	for(var i=0;i<data.length;i++){
    		var da = data[i];
    		index.GlobelVehicle.put(da.id,data[i]); 
    		if(data[i].TYPE=="2"){
    			/*index.terminalMap.put(data[i].VID,data[i].CommNO);
    			index.vehicleMap.put(data[i].VID,data[i].NAME);
    			index.GlobalVehilceNo.put(data[i].NAME,data[i].VID);*/
    			//index.vehicleNoColor.put(da.);
    		}
    	}
    },
    /**
     * 当前用户车辆的上线状态
     */
    getVehicleStatus : function(tableData){
    	var _this = this;
    	if(_this.getVehicleStatusTimer){
    		clearTimeout(_this.getVehicleStatusTimer);
    	}
    	var getTimestamp=new Date().getTime();
    	var noColor = this.vehicleNoColor.values().join();
    	//var noColorStr = noColor;
    	//noColorStr = 
        $.ajax({
            type: 'POST',
        	url : appCtx+'gis/monitor/queryVehicleStatus.html',
            data : {v:getTimestamp,vehicle_no_color:noColor},
            success : function(data){
                if(data){
                	var online= JSON.parse(data);
                	var offline;
                	var isonline = $('#vehicleSeachTable').find('.isonline');
                	for(var i=0;i<tableData.length;i++){
                		var da = tableData[i];
                		var indexs = online.indexOf(da.noColor);
                		if( indexs > -1){
//                			da.noColor = online[indexs];
                			isonline.eq(i).removeClass('isonline_false').addClass('isonline_true');
                		}else{
//                			da.noColor = online[indexs];
                			isonline.eq(i).removeClass('isonline_true').addClass('isonline_false');
                		}
                	}
                	/*var da = JSON.parse(data);
                    var offline = da.offline;
                    var online = da.online;
                    index.onlineVehicleStr=da.online;
                    var offlineLen = offline.length;
                    var onlineLen = online.length;
                    // 刷新树的图标
                    var getNodes =  $.fn.zTree.getZTreeObj("carTreeList");
                    var nodes = getNodes.transformToArray(getNodes.getNodes());
                    var len = nodes.length;
                    for(var i=0;i<len;i++){
                    	if(nodes[i].iconSkin){
                    		global.vaild();
                    		if(offline.indexOf(nodes[i].VID)>-1){
                    			if(nodes[i].isPublicNet > 0){
                    				nodes[i].iconSkin = 'videoOffline';
                    			}else{
                    				nodes[i].iconSkin = 'offline';
                    			}
                        	}else if(online.indexOf(nodes[i].VID)>-1){
                        		if(nodes[i].isPublicNet > 0){
                        			nodes[i].iconSkin = 'videoOnline';
                    			}else{
                    				nodes[i].iconSkin = 'online';        				
                    			}
                        	}
                        	getNodes.updateNode(nodes[i]);
                    	}
                    }
                    //统计 第一级企业在线数
                    var nodes = index.carTree.getNodes();
                    for(var i=0;i<nodes.length;i++){
                    	var vehicles = nodes[i].VehicleCount;
                    	var vehiclesLen = vehicles.length;
                    	var count = 0;
                    	for(var j=0;j<vehiclesLen;j++){
                    		if(global.arr.contains(online,vehicles[j])){
                    			count++;
                    		}
                    	}
                    	nodes[i].NAME = nodes[i].WorkUnitName+"("+count+"/"+nodes[i].VehicleCount.length+")";
                    	getNodes.updateNode(nodes[i])
                    } */               
                }else{
                }
            }
        });
        //一分钟刷新一次车辆上线线
        _this.getVehicleStatusTimer = setTimeout(function(){
            _this.getVehicleStatus(tableData);
        },6000*60);
	}, 
    /**
     * 查询结果表格
     * */
    initTableData : function(){
    	var _this = this;
        var formmatAction = function (ID,registration_no,vin,terminal_id,isonline,isPublicNet){
            var name = vin;
            if(registration_no != "" && registration_no != "undefined" && registration_no != "null"){
                name = name + " (" + registration_no + ")";
            }
            var className = 'isonline_'+isonline + ' ' + 'isonline';
            if(isPublicNet=="-1"){
            	className = 'isonline_'+isonline + ' ' + 'isonline';
            }else{
            	className = 'isonlineVideo_'+isonline + ' ' + 'isonline';
            }
            var colname = '<span class="'+className+'" style="vertical-align:middle;margin-right:5px;"></span><span>'+name+'</span></div>';
            return colname;
        };
        
        var formmatActionOnline = function(vehicle_no){
        	var str = '<i class="isonline isonline_false"></i><span style="display:inline-block;width:70px;">'+vehicle_no+'</span>';
        	return str;
        	
        };
        
        $("#vehicleSeachTable").flexigrid({
            dataType : 'json',
            colModel : [{
                display : '车牌号',
                name : 'Handler',
                width : 120,
                sortable : false,
                align : 'center',
                paramcolnames : ['vehicle_no'],
                handlefunction:formmatActionOnline
            },{
                display : '车牌颜色',
                name : 'vehicle_color_name',
                width : 95,
                sortable : false,
                align : 'center'
//            },{
//                display : '车牌号(自编号)',
//                name : 'Handler',
//                width : 220,
//                sortable : false,
//                align : 'left',
//                paramcolnames:["id","internalNumber","vehicle_no","terminalId","isonline","isPublicNet"],
//                handlefunction:formmatAction
            }],
            resizable : false,
            resizableTable:false,
            sortname : "id",// 第一次加载数据时排序列
            sortorder : "desc",// 第一次加载数据时排序类型
            usepager : false,// 是否分页，默认为true。
            showToggleBtn : false,
            showTableToggleBtn : false,// 是否显示收起/打开按钮,默认不显示。
            checkbox : true,// 是否要多选框,默认为false。
            rowId : 'id',// 多选框绑定行的id,只有checkbox : true时才有效。
            singleSelect : true,
            width : 'auto',// 表格宽度
            height : index.flexigridH, // 表格高度
            titDisplay:false,
            onSuccess : function(data){
            	/*$("#vehicleSeachTable").find("input[type=checkbox]").each(function() {
					$(this).attr("id","ck_" + $(this).val()).css({"margin-top" : 0});
				}); */
            	index.resetDetail();
            	index.vehicleID = null;
            	mapTool.clearAllMarker();
            	index.vehicleNoColor.clear();
            	index.vehicleColor.clear();
            	for(var i=0;i<data.rows.length;i++){
            		var da = data.rows[i];
            		da.isonline = false;
            		var noColor = da.vehicle_no + '_' + da.vehicle_color;
            		da.noColor = noColor;
            		index.vehicleNoColor.put(da.id,noColor);
            		index.vehicleColor.put(da.id,da.vehicle_color);
            	}
            	index.initTerminalMap(data.rows);
            	index.getVehicleStatus(data.rows);
            },
            onSelectRow : function(data,title,checked){
            	//var checked = $("#ck_"+data.id).attr("checked");
            	index.vehicleID = data.id;
            	var vehicleNoColor = data.vehicle_no + '_' + data.vehicle_color;
            	if(checked){
            		index.arrayObj.push(vehicleNoColor);
            		_this.loadBaseInfo(data,"grid");  // 增加   对右下实时和基础信息的刷新
            	}else{
            		global.arr.removeElm(index.arrayObj,vehicleNoColor);
            		mapTool.clearMarker(data.id);
            		//if(){}
            		if(_this.loadBaseInfoId = data.id){
            			_this.resetDetail();
            			index.infoWindow.close();
            		}
            	}
            	data.noColor = vehicleNoColor;
            	index.arrayObj = global.arr.removeRepeat(index.arrayObj);
            	//_this.queryDriverInfo(encodeURI('贵CU8028_2'));
            	//var item = index.GlobelVehicle.get(data.id);
            	//var params = index.arrayObj.join(',');
            	index.subScribe();
            	return;
//            	index.detailInit.clickCar(0);
//            	var item = index.GlobelVehicle.get(data.id);
//                index.loadBaseInfo(item,"grid");  // 增加   对右下实时和基础信息的刷新
//                var jsonData = index.GlobelSubScribeVehicle.get(data.id);		
//        		if(jsonData){
//        			index.loadBaseInfo(item,"grid");
//        			index.detailInit.clickCar(0);
//        			$(".car-sd").text(jsonData.gpsSpeedF);
//    	           	$(".car-millage").text(jsonData.gpsMileageF);
//    	           	$(".car-time").text(jsonData.gpsTimeStr);
//    	       		$(".car-staue").text(jsonData.status);
//    	       		$(".car-staue").attr("title",jsonData.status);
//    	           	var address=mapTool.getAddress("caraddress",jsonData);
//    	           	if(address){
//    	           		$("#caraddress").html(address);
//    	           	}
//        		}
//            	var checked = $("#ck_"+data.id).attr("checked");
//            	var id = data.id;
//            	var vehileNode = index.carTree.getNodesByParam("VID", id, null);
//            	if (checked) {
//            		var vids =$("#vehicleSeachTable").getCheckedRows();
//            		var vidsLen = vids.length;
//            		for(var i=0;i<vidsLen;i++){
//            			if(index.terminalMap.get(vids[i])){
//            				index.arrayObj.push(index.terminalMap.get(vids[i]));
//            			}	
//            		}; 
//            		index.arrayObj=global.arr.removeRepeat(index.arrayObj);
//            		index.subScribe(index.arrayObj.toString());
//            		index.carTree.checkNode(vehileNode, true, true);    // 同步到树
//            		if (vehileNode != null && vehileNode.length > 0) {
//            			index.carTree.checkNode(vehileNode[0], true, true);
//            		}
//
//            	} else {
//            		if (vehileNode != null && vehileNode.length > 0) {
//            			index.carTree.checkNode(vehileNode[0], false, true);// 同步到树
//            			global.arr.removeElm(index.arrayObj,index.terminalMap.get(vehileNode[0].VID));
//            			mapTool.clearMarker(vehileNode[0].VID);
//            			index.GlobalGpsCache.remove(vehileNode[0].VID);
//            		}
//            		if(index.arrayObj.length>0){
//            			index.subScribe(index.arrayObj.toString());
//            		}else{	
//            			clearInterval(index.vehicleArrayTimer);
//            			index.GlobalGpsCache.clear();
//            			index.myGrid.clearAll();
//            			index.vehicleStatus=[0,0,0,0];     			
//            		}
//            		$(".all-num").text(index.vehicleStatus[0]);
//             		$(".run-num").text(index.vehicleStatus[1]);
//             		$(".stop-num").text(index.vehicleStatus[2]);
//             		$(".dropped-num").text(index.vehicleStatus[3]);
//            	}
            },
            onSelectAllRow : function(data,checked){
            	//var ids =$("#vehicleSeachTable").getCheckedRows();
            	if(checked){
            		index.arrayObj = [];
            		for(var i=0;i<data.length;i++){
            			
            			//var vehileNode = index.carTree.getNodesByParam("VID", data[i].id, null);
            			/*if(index.terminalMap.get(data[i].id)){
            				index.arrayObj.push(index.terminalMap.get(data[i].id));
            			}*/
            			index.arrayObj=global.arr.removeRepeat(index.arrayObj);
                		/*index.carTree.checkNode(vehileNode, true, true);    // 同步到树
                		if (vehileNode != null && vehileNode.length > 0) {
                			index.carTree.checkNode(vehileNode[0], true, true);
                		}*/
            			index.arrayObj.push(data[i].vehicle_no + '_' + data[i].vehicle_color);
            		}
            		//index.subScribe(index.arrayObj.join(','));
            	}else{
            		index.arrayObj = [];
            		/*for(var i=0;i<data.length;i++){
            			var vehileNode = index.carTree.getNodesByParam("VID", data[i].vehicleId, null);
            			if (vehileNode != null && vehileNode.length > 0) {
                			index.carTree.checkNode(vehileNode[0], false, true);// 同步到树
                			global.arr.removeElm(index.arrayObj,index.terminalMap.get(vehileNode[0].VID));
                			mapTool.clearMarker(vehileNode[0].VID);
                		}
            			if(index.arrayObj.length>0){
                			index.subScribe(index.arrayObj.toString());
                		}else{
                			clearInterval(index.vehicleArrayTimer);
                			index.GlobalGpsCache.clear();
                			index.myGrid.clearAll();
                			index.vehicleStatus=[0,0,0,0]; 
                			if(index.MARKID){
                				index.MARKID=null;
                				index.infoWindow.close();
                			}
                		}
            			$(".all-num").text(index.vehicleStatus[0]);
                 		$(".run-num").text(index.vehicleStatus[1]);
                 		$(".stop-num").text(index.vehicleStatus[2]);
                 		$(".dropped-num").text(index.vehicleStatus[3]);
            		}*/
            	} 
            	index.subScribe(index.arrayObj.join(','));
            }/*,
            onSelectRightRow : function(data,x,y,offsetX,offsetY){
            	var noColor = data.vehicle_no + '_' + data.vehicle_color;
            	noColor = index.base64.encode(noColor);
            	$('.playbackurl a').attr('href',appCtx+'gis/playback/trackPlayBack.html?vehicle_no_color='+noColor);
            	$('.videourl a').attr('href',appCtx+'video/videoMonitorMT.html?vehicleID='+noColor);
            	$('.monitorurl a').attr('href',appCtx+'gis/monitor/multiVehicleMonitor.html?vehicleID='+noColor);
            	$('.multivideourl a').attr('href',appCtx+'video/videoMonitorMT.html?vehicleID='+noColor);
            	//$('.shareVehicleurl a').attr('href',appCtx+'video/videoMonitorMT.html?vehicleID='+noColor); 
            	if($('.detail-more').is(':hidden')){
            		$('.detail-more').css({
            			display: 'block',
            			top: offsetY
            		});
            	}
            }*/
        });
    },
    /**
     *   刷新实时和基础面板
     * @param data
     */
    loadBaseInfo : function(data,grid,item){ 
    	//this.queryDriverInfo();
    	this.loadBaseInfoId = data.id;
    	this.queryDriverInfo(encodeURI(data.noColor));
    	var $carDetail = $('.car-details');
    	$carDetail.find('.platform_name').html(data.platform_name);
    	$carDetail.find('.vehicle_no').html(data.vehicle_no);
    	$carDetail.find('.ent_name').html(data.enterprise_name);
    	$carDetail.find('.vehicle_color_name').html(data.vehicle_color_name);
    	$carDetail.find('.trade_kind_name').html(data.tradeName);
    	/*var $detailMore = $('.detail-more');
    	var noColor = index.base64.encode(data.noColor);
    	$detailMore.find('.playbackurl a').attr('href',appCtx+'gis/playback/trackPlayBack.html?vehicle_no_color='+ noColor);
    	$detailMore.find('.videourl a').attr('href',appCtx+'video/videoMonitor.html?vehicle_no_color='+ noColor);
    	$detailMore.find('.monitorurl a').attr('href',appCtx+'gis/monitor/multiVehicleMonitor.html?vehicle_no_color='+ noColor);
    	$detailMore.find('.multivideourl a').attr('href',appCtx+'video/videoMonitorMT.html?vehicle_no_color='+ noColor);
    	index.resetDetail();*/
    	/*var terminalID = data.TID;
    	var CommNO = data.CommNO;*/
		index.vehicleID=data.id;
		 /*$(".car-track").removeAttr("disabled");
		 $(".car-video").removeAttr("disabled");
		 $(".car-num").text(data.NAME);
		 $(".car-remark").text(data.REMARK);*/
		 if(item){
			 var gpsSpeedF = item.gpsSpeedF;
			 var gpsMileage = item.gpsMileage;
			 if(typeof (gpsSpeedF) == 'string'){
				gpsSpeedF = JSON.parse(gpsSpeedF).toFixed(1);
			 }else{
				gpsSpeedF = gpsSpeedF.toFixed(1);
			 }
			 if(typeof (gpsMileage) == 'string'){
			 	gpsMileage = JSON.parse(gpsMileage).toFixed(1);
			 }else{
			 	gpsMileage = gpsMileage.toFixed(1);
			 }
			 $(".car-sd").text(parseInt(gpsSpeedF) + 'km/h');
	         $(".car-millage").text(parseInt(gpsMileage) + 'km');
	         $(".car-time").text(item.gpsTimeS);
	       	 $(".car-staue").text(item.status);
	       	 $(".car-staue").attr("title",item.status);
	         var address=mapTool.getAddress("caraddress",item);
	         if(address){
	           	$("#caraddress").html(address);
	         }
		 }
		 /*if(data.DNAME){
			 $(".car-driver").text(data.DNAME); 
		 }
		 if(data.PHONE){
			 $(".car-phone").text(data.PHONE);
		 }
		 if(grid){
			 
		 }else{
			 index.arrayObj.push(CommNO);
			 index.arrayObj=global.arr.removeRepeat(index.arrayObj);
			 index.subScribe(index.arrayObj.toString()); 
		 }	*/
    },
    /**
     * 初始化订阅表格
     */
    initSubscribeTable : function(){
    	var initOptions = [
        {	// 表格配置
           tableId:'gridbox',
           header:'操作,车牌号,车牌颜色,ACC,状态,精度,定位时间,速度,脉冲速度,里程,位置信息',
           colTypes:'cancelBtn,TrackingBtn,ro,ro,carStatus,ro,ro,ro,ro,ro,ro',
           code :'Handler,vehicleId,vehicleChinaColor,accChainaStatus,carStatus,validS,gpsTimeS,gpsSpeedF,pulseSpeedF,gpsMileage,address',
           initWidths:'120,120,80,80,50,50,125,50,60,60,210',
           initWidthps:'120,120,80,80,50,50,125,50,60,60,510',
           align:'left,left,left,left,center,left,left,left,left,left,left',
           sort:',str,str,str,str,str,str,int,int,int,str'
    	 }];
    	 var obj = initOptions[0];
    	 index.myGrid = new dhtmlXGridObject(obj.tableId);
         //grid.setImagePath("../imgs/");//设置grid中引用图片路径，如排序图片，checkbox图片，背景等
    	 index.myGrid.setHeader('操作,车牌号,车牌颜色,ACC,状态,精度,定位时间,速度,脉冲速度,里程,位置信息',null,["text-align:left;","text-align:left;cursor:pointer;","text-align:left;","text-align:left;","text-align:left;","text-align:left;cursor:pointer;","text-align:left;cursor:pointer;","text-align:left;cursor:pointer;","text-align:left;cursor:pointer;","text-align:left;","text-align:left;"]);//列标题
    	 index.myGrid.setInitWidths(obj.initWidths);//各列宽度数字表示像素，弹性用*表示
    	 //index.myGrid.setInitWidthsP(obj.initWidthps)
    	 index.myGrid.setColumnIds(obj.code);
    	 index.myGrid.setColAlign(obj.align);//设置列数据的水平布局
    	 index.myGrid.setColTypes(obj.colTypes);//设置列数据的数据类型(ch ---- checkbox; ra ---- radio;ro ---- readonly，双击具体某项数据时不可编辑的;txt ---- 显示的是字符串，双击某项数据会弹出编辑页面 )
    	 index.myGrid.setColSorting(obj.sort);
    	 index.myGrid.setSkin("dhx_skyblue");//指明使用什么皮肤
    	 index.myGrid.enableAutoHeight(false,'auto',true);
    	 //index.myGrid.enableAutoHeight(false);
    	 //index.myGrid.enableAutoWidth(true);
    	 index.myGrid.init();
    	 index.myGrid.enablePreRendering(30);
    	 index.myGrid.enableSmartRendering(true);
    	 index.myGrid.attachEvent("onRowSelect",function(id,ind){
    	 var jsonData = index.GlobelSubScribeVehicle.get(id);		
    		if(jsonData && ind != 0){
    			index.vehicleID = id;
    			var item = index.GlobelVehicle.get(id);
    			index.loadBaseInfo(item,"grid",jsonData);
    			mapTool.setCenter(jsonData);
    			
    			if(ind>0){
    				index.showCar=true;
    				index.addMarkerForClick(jsonData);//设置车辆图标的颜色
    				index.GlobaljsonData=jsonData;
    				index.jsonArr=jsonData.commNO;
    			}    
    			
    			index.detailInit.clickCar(0);
    			var gpsSpeedF = jsonData.gpsSpeedF;
    			var gpsMileage = jsonData.gpsMileage;
   			 	if(typeof (gpsSpeedF) == 'string'){
   			 		gpsSpeedF = JSON.parse(gpsSpeedF).toFixed(1);
   			 	}else{
   			 		gpsSpeedF = gpsSpeedF.toFixed(1);
   			 	}
   			 	if(typeof (gpsMileage) == 'string'){
   			 		gpsMileage = JSON.parse(gpsMileage).toFixed(1);
			 	}else{
			 		gpsMileage = gpsMileage.toFixed(1);
			 	}
    			$(".car-sd").text(parseInt(gpsSpeedF) + 'km/h');
	           	$(".car-millage").text(parseInt(gpsMileage) + 'km');
	           	$(".car-time").text(jsonData.gpsTimeStr);
	       		$(".car-staue").text(jsonData.status);
	       		$(".car-staue").attr("title",jsonData.status);
	           	var address=mapTool.getAddress("caraddress",jsonData);
	           	if(address){
	           		$("#caraddress").html(address);
	           		$("#caraddress").attr("title",address);
	           	}
    		}
    	 });
    },
    /**
     * 订阅（树）
     * @param e
     * @param treeId
     * @param treeNode
     */
    zTreeOnCheck : function(e, treeId, treeNode){
    	if (treeNode.TYPE == 1) {// 企业
    		var terminalList = []; // 
    		var terminal = new HashMap();
    		var childrenNode = index.carTree.transformToArray(treeNode);// 取得所有下级
    		var commnoList =[];
    		var childrenNodeLen = childrenNode.length;
    		if(childrenNodeLen>500&&treeNode.checked){
    			childrenNodeLen=500;
    			global.ajaxLoading.pop("订阅超出500台,只订阅前500台",true,1000);
    		}
    		var start = new Date().getTime();
    		for (var i = 0; i < childrenNodeLen; i++) {
    			if (childrenNode[i].TYPE == 2) {
    				if(treeNode.checked){          //勾选加 terminalID
    					var vehicleID = childrenNode[i].VID;
    					var commNo = childrenNode[i].CommNO;
    					terminal.put(vehicleID,commNo);
        				terminalList.push(terminal);
        				index.arrayObj.push(commNo);
        				$("#ck_"+vehicleID).attr("checked", "checked");
    				}else{              // 取消勾选，清除terminalID    					
    					var vehicleID = childrenNode[i].VID.toString();
    					var commNo = childrenNode[i].CommNO;
    					terminal.put(vehicleID,commNo);
    					terminalList.push(terminal);
    					mapTool.clearMarker(vehicleID);
    					global.arr.removeElm(index.arrayObj,commNo);
    					$("#ck_"+vehicleID).removeAttr("checked");
    					index.GlobalGpsCache.remove(vehicleID);
    					if(index.arrayObj.length>0){
//    						index.subScribe(index.arrayObj.toString());
    					}else{
    						
    						index.vehicleStatus=[0,0,0,0];	
    						$(".all-num").text(index.vehicleStatus[0]);
        					$(".run-num").text(index.vehicleStatus[1]);
        					$(".stop-num").text(index.vehicleStatus[2]);
        					$(".dropped-num").text(index.vehicleStatus[3]);
        					if(index.MARKID){
        						index.MARKID=null;
                				index.infoWindow.close();
                			}
    					}
    						
    				}			
    			}
    		}	
    		if (terminalList.length > 0) {
    			if (treeNode.checked) {
    				index.arrayObj=global.arr.removeRepeat(index.arrayObj);
    				index.subScribe(index.arrayObj.toString());// 订阅
    			} else {
    				index.unSubscribe(terminalList);
    				index.subScribe(index.arrayObj.toString()); //取消之后的重新订阅 
    			}
    		}
    	} else {// 车辆
    		var terminal = new HashMap();
    		var vehicleID = treeNode.VID;
    		var commNo = treeNode.CommNO;
    		terminal.put(vehicleID,commNo);
    		if (treeNode.checked) {
    			index.arrayObj.push(commNo);
    			index.arrayObj=global.arr.removeRepeat(index.arrayObj);
    			index.subScribe(index.arrayObj.toString());
    			$("#ck_"+vehicleID).attr("checked", "checked");
    		} else {
    			index.unSubscribe(commNo);
    			global.arr.removeElm(index.arrayObj,commNo);
    			index.subScribe(index.arrayObj.toString()); //取消之后的重新订阅 
    			$("#ck_"+vehicleID).removeAttr("checked");
    			mapTool.clearMarker(vehicleID);
    			index.GlobalGpsCache.remove(vehicleID);
    			if(index.arrayObj.length>0){
//					index.subScribe(index.arrayObj.toString());
				}else{
					
					index.vehicleStatus=[0,0,0,0];	
					$(".all-num").text(index.vehicleStatus[0]);
					$(".run-num").text(index.vehicleStatus[1]);
					$(".stop-num").text(index.vehicleStatus[2]);
					$(".dropped-num").text(index.vehicleStatus[3]);
					if(index.MARKID){
						index.MARKID=null;
        				index.infoWindow.close();
        			}
				}
    		}
    	}
    },
    /**
     * 重置实时和基础信息
     */
    resetDetail : function(){
    	/*$(".car-num").text("");
   	 	$(".car-sd").text("");
   	 	$(".car-millage").text("");
   	 	$(".car-time").text("");
   	    $(".car-staue").text("");
   	    $(".car-remark").text("");
   	    $(".car-driver").text("");
   	    $(".car-phone").text("");
   	    $(".car-address").text(""); */	
    	var $carDetail = $('.car-details');
    	$carDetail.find('.car-ont').html('');
    	/*$carDetail.find('.platform_name').html('');
    	$carDetail.find('.vehicle_no').html('');
    	$carDetail.find('.ent_name').html('');
    	$carDetail.find('.vehicle_color_name').html('');
    	$carDetail.find('.trade_kind_name').html('');*/
    },
    /**
     * 树节点单击，获取实时和基础信息
     * @param e
     * @param treeId
     * @param treeNode
     */
    zTreeOnClick : function(e,treeId, treeNode){
//    	index.detailInit.clickCar(0);
//    	index.resetDetail();  	
    	var	level = treeNode.LEVEL;
    	if(level == 4){
    		var enterpriseId = treeNode.ID.replace("ent_","");
    		var paramsGrid = [{
                name : 'enterpriseId',
                value : enterpriseId
            }];
    		index.enterpriseId = enterpriseId;
    		index.PF_Name = treeNode.PF_Name;
    		index.subName = treeNode.NAME.split('(')[0];
    		index.treeTabInit.searchFunc(1);
    		index.myGrid.clearAll();
    		$("#vehicleSeachTable").flexOptions({
        		url : appCtx+'gis/monitor/queryVehicleByEnt.html',
        		newp : 1,// 设置起始页
        		params : paramsGrid
        	}).flexReload();// 重新加载  
    		index.arrayObj = [];
    		index.subScribe();
    	}
    	
//    	if(treeNode.TYPE==2){
//    		index.carTree.checkNode(treeNode, true, true);
//    		index.vehicleID=treeNode.VID;
//    		index.GlobelVehicle.put(treeNode.VID,treeNode);
//    		 $(".car-num").text(treeNode.NAME);
//    		 $(".car-remark").text(treeNode.REMARK);
//    		 if(treeNode.DNAME){
//    			 $(".car-driver").text(treeNode.DNAME); 
//    		 }
//    		 if(treeNode.PHONE){
//    			 $(".car-phone").text(treeNode.PHONE);
//    		 }
//    		index.arrayObj.push(CommNO);
// 			index.arrayObj=global.arr.removeRepeat(index.arrayObj);
//    		index.subScribe(index.arrayObj.toString());
//    	};   	
    },
    /**
     * 树节点打开，计算打开企业的上线车
     */
    zTreeOnExpand : function(e, treeId, treeNode){
    	for (var i = 0; i < treeNode.children.length; i++) {
    		var childrenNode = treeNode.children[i];
    		if (childrenNode.TYPE == 1) {// 企业
            	var vehicles = childrenNode.VehicleCount;
            	var count = 0;
            	for(var j=0;j<vehicles.length;j++){
            		if(index.onlineVehicleStr&&global.arr.contains(index.onlineVehicleStr,vehicles[j])){
            			count++;
            		}
            	}
            	childrenNode.NAME = childrenNode.WorkUnitName+"("+count+"/"+childrenNode.VehicleCount.length+")";
            	index.carTree.updateNode(childrenNode);
    		}
    	}
    },
    /**普通查询*/
    searchTable : function(){
        var sarchVal = $.trim($('.search-input').val());
        var paramsGrid = [{
            name : 'vehicle_no',
            value : sarchVal
        }];
        $("#vehicleSeachTable").flexOptions({
    		url : appCtx+'gis/monitor/queryVehicleByCondition.html',
    		newp : 1,// 设置起始页
    		params : paramsGrid
    	}).flexReload();// 重新加载  
        index.arrayObj = [];
		index.subScribe();
    },
    /**
     * 勾选订阅
     */
    subScribe : function(){
    	var _this = this;
    	var params = index.arrayObj.join(',');
   	 var getSubScribeDataVehicles = function(params){
   		 if(params == ""){
   			 index.cancelAll();
   			 return;
   		 }
   		 var getTimestamp=new Date().getTime();
   		 $.ajax({
              url : appCtx+'gis/monitor/subScribe.html',
              data : {"vehicle_no_color":encodeURI(params),v:getTimestamp},
              dataType :'json',
              success : function(result){
            	  if(_this.subScribeTime){
            		  if(_this.subScribeTime > result.v){
            			  return;
            		  }
            	  }
            	  _this.subScribeTime = result.v;
            	  var data = result.data;
            	  if(_this.arrayObj.length == 0){
            		  return;
            	  };
                  if(data){ 
                	    $("#cancel").css("display","block");
	                  	index.vehicleStatus=[0,0,0,0];
	               		index.vehicleStatus[0]=data.length;
	               		index.allNum=new Array();
	               		index.runNum=new Array();
	               		index.stopNum=new Array();
	               		index.droppedNum=new Array();
	               		index.GlobalGpsCache.clear();
	               		for(var i=0;i<data.length;i++){ 
	               			var da = data[i];
	               			if(index.GlobalAddress.get(da.vehicleId)){
	               				da.address=index.GlobalAddress.get(da.vehicleId);
	               			}
	               			mapTool.clearMarker(da.vehicleId);
	             			index.addMarker(da);
	             			index.allNum.push(da);
	               			if(data[i].carStatus==1){
	               				index.runNum.push(da);
	               				index.vehicleStatus[1]++;
	               			}else if(da.carStatus==2){
	               				index.stopNum.push(da);
	               				index.vehicleStatus[2]++;
	               			}else{
	               				index.droppedNum.push(da);
	               				index.vehicleStatus[3]++;
	               			};
	               			
	               			if(da.vehicleId==index.vehicleID){
	               				 var gpsSpeedF = da.gpsSpeedF;
	               				 var gpsMileage = da.gpsMileage;
	               				 if(typeof (gpsSpeedF) == 'string'){
	               					gpsSpeedF = JSON.parse(gpsSpeedF).toFixed(1);
	               				 }else{
	               					gpsSpeedF = gpsSpeedF.toFixed(1);
	               				 }
	               				 if(typeof (gpsMileage) == 'string'){
	               			 		gpsMileage = JSON.parse(gpsMileage).toFixed(1);
	            			 	 }else{
	            			 		gpsMileage = gpsMileage.toFixed(1);
	            			 	 }
	               				 $(".car-sd").text(parseInt(gpsSpeedF) + 'km/h');
		                    	 $(".car-millage").text(parseInt(gpsMileage) + 'km');
		                    	 $(".car-time").text(da.gpsTimeS);
	                    		 $(".car-staue").text(da.status);
	                    		 $(".car-staue").attr("title",da.status);
		                    	 var address=mapTool.getAddress("caraddress",da);
		                    	 da.address="123456";
		                    	 if(address){
		                    		 $("#caraddress").html(address);		                    				                    		 
		                    	 }
	               			};
	               			da.vehicleChinaColor = global.carColor(da.vehicleColor);
	               			da.accChainaStatus = da.accStatus ? 'ACC开' : 'ACC关';
	               			if(index.detailGridInit.index()==0){
	               				index.handTrack(da);
	               			}else if(index.detailGridInit.index()==1){
	               				if(da.carStatus==1){
	               					index.handTrack(da);
	               				}
	               			}else if(index.detailGridInit.index()==2){
	               				if(da.carStatus==2){
	               					index.handTrack(da);
	               				}
	               			}else if(index.detailGridInit.index()==3){
	               				if(da.carStatus==3){               					
	               					index.handTrack(data[i]);
	               				}
	               			}		
	               			index.GlobelSubScribeVehicle.put(da.vehicleId,da);
//	               			if(data[i].vehicleId==0){
//	               				console.log("后端返回vehicleId=0  需要处理redis缓存数据的  终端ID 为： "+data[i].terminalId);
//	               			}
	               		}
	               		index.reloadGridData();
	               		$(".all-num").text(index.vehicleStatus[0]);
	               		$(".run-num").text(index.vehicleStatus[1]);
	               		$(".stop-num").text(index.vehicleStatus[2]);
	               		$(".dropped-num").text(index.vehicleStatus[3]);
                  }else{
	                 	var vehicleStatus=[0,0,0,0];
	                    $(".all-num").text(vehicleStatus[0]);
	               		$(".run-num").text(vehicleStatus[1]);
	               		$(".stop-num").text(vehicleStatus[2]);
	               		$(".dropped-num").text(vehicleStatus[3]);
	               		clearInterval(index.vehicleArrayTimer);
                  }
              }
          });
        };
     getSubScribeDataVehicles(params);
     clearInterval(index.vehicleArrayTimer);
   	 index.vehicleArrayTimer = setInterval(function(){
   		 getSubScribeDataVehicles(params);
   	 },30000);
    },
    /**
     * 取消订阅
     */
    unSubscribe : function(){
    	index.myGrid.clearAll();
    },
    /**
     * 处理定位数据
     */
    handTrack : function(jsonData){
//    	var GlobalGridField = ['vehicleId','vehicleNo','carStatus','validS','gpsTimeStr','gpsSpeedF','pulseSpeedF','gpsMileageF','status','address'];
    	var tmpData = [],tmpValue = null;
    	for(var i = 0; i < index.GlobalGridField.length; i++){
    		tmpValue = jsonData[index.GlobalGridField[i]];

    		if(tmpValue != undefined && tmpValue != null)
    			tmpData.push(tmpValue);
    		else
    			tmpData.push("");
    	}
    	var gridData = {id:jsonData.vehicleId,data:tmpData};
    	index.GlobalGpsCache.put(jsonData.vehicleId,gridData);
    },
    timer : function(){
    	 var subscribetimer;
    	 var funstart = function(){
    		 subscribetimer=setInterval(function(){
        		 index.subScribe();
        	 },20000); 
    	 }
    	 var funend = function(){
    		 clearInterval(subscribetimer);
    	 }
    	 return {
    		 funstart:function(){funstart();},
    		 funend:function(){funend();}
    	}
    	
    },
    /**
     * 导出
     */
    exportExcel : function(){
    	var result = '';
    	if(index.myGrid != undefined){
    		var idArray = index.myGrid.getAllRowIds().split(",");
    		for(var i = 0; i < idArray.length; i++){
    			index.myGrid.forEachCell(idArray[i],function(cellObj,ind){
    				if (ind > 0) {
    					if(1 == ind){
    						var htmls  = cellObj.getValue().match(/>\S+\</);
    						if (htmls!=null) {
    							result += htmls[0].replace(/[<|>]/g,"") + '#';
    						}
    					}else if(2 == ind){
    						var htmls  = cellObj.getValue().match(/>\S+\</);
    						if (htmls!=null) {
    							var temp = htmls[0].replace(/[<|/>]/g,"").replace("div","");
    							if(temp==1){
    								temp="运行";
    							}else if(temp==2){
    								temp="停车";
    							}else if(temp==3){
    								temp="掉线";
    							}
    							result += temp + '#';
    						}
    					}else{
    						result += cellObj.getValue() + '#';
    					}
    				}
                });
                result += '&';
            }
    		if(result.length > 0){
    			index.exportExc(appCtx+"gis/monitor/exportExcel.html?time="+ new Date(), {data:result,name:"Monitor"});
    		}else{
    			global.ajaxLoading.pop('暂无数据可导出', true, 2000);
    		}
    	}else{
    		global.ajaxLoading.pop('该表不支持导出!', true, 2000);
    	}
    },
    /**
     * 导出拼装
     * @param url
     * @param params
     */
    exportExc : function(url, params) {    
        var temp = document.createElement("form");        
        temp.action = url;        
        temp.method = "post";        
        temp.style.display = "none";  
        
        var opt1 = document.createElement("input");        
        opt1.name = "name";        
        opt1.value = params.name;
        opt1.type = "hidden";
        temp.appendChild(opt1); 
        
        
        var subLocationArrays = index.getSubParams(params.data);
        for (var i = 0; i < subLocationArrays.length; i++) {        
            var opt = document.createElement("input");        
            opt.name = "subData"+i;        
            opt.value = (subLocationArrays[i]).join("&");        
            temp.appendChild(opt);        
        }   
        document.body.appendChild(temp);   
        temp.submit();        
    },
    /**
     * 导出数据处理
     * @param data
     * @returns {Array}
     */
    getSubParams : function(data) {
    	var locationRows = data.split("&");
    	var i = locationRows.length / 100;
    	var subLocationRows = new Array();
    	for (var j = 0;j < i ; j++) {
    		subLocationRows.push(locationRows.slice(j*100,(j+1)*100));
    	}
    	return subLocationRows;
    },
    /**
     * 指令发送
     */
    sendCommand : function(params){
//    	console.log(params);
    	if(index.vehicleID){
			var data = index.GlobelVehicle.get(index.vehicleID);
			var getTimestamp=new Date().getTime();
			$.ajax({
	               url : appCtx+'gis/monitor/sendCommand.html?v='+getTimestamp,
	               data : {"vehicleId":data.VID,"terminalId":data.TID,"terminalType":data.TerminalType,"commno":data.CommNO,"commandId":params.commandId,"cmdArgs":params.cmdArgs,"commandType":params.commandType},
	               dataType :'json',
	               success : function(item){
	                   if(item.result=="0"){   //  发送成功  获取指令回复
	                	   if(item.flag==0){
	                		   index.uuidCache.put(item.uuid,data);
	                		   index.getCommandReply(item);     		     
	                		   global.ajaxLoading.pop("指令下发到终端",true,1000);
	                	   }else{
	                		   global.ajaxLoading.pop("指令下发失败,原因："+item.resultName,true,1000);
	                	   }    
	                   }else{
	                	   global.ajaxLoading.pop("指令下发超时，未收到终端回执",true,1000);
	                   }
	                   $(".textarea-order").val("");
	               }
	         });
		 }else{
			 global.ajaxLoading.pop("请选择车辆",true,1000);
		 } 	 
    },
    getCommandReply : function(data){
    	if(data){
    		var getTimestamp=new Date().getTime();
    		var params = index.uuidCache.get(data.uuid);
    		$.ajax({
	               url : appCtx+'gis/monitor/getCommandReply.html?v='+getTimestamp,
	               data : {"terminaltype":params.TerminalType,"commno":params.CommNO,"commandId":data.commandId,"cmdPkgSeq":data.cmdPkgSeq,"terminalId":params.TID,"commandTime":data.commandTime,"uuid":data.uuid},
	               dataType :'json',
	               success : function(item){
//	            	   console.log(item);
	                   if(item.result){   //  获取指令回复
	                	   if(item.replyCode=="33536"&&item.uuid==data.uuid){
	                		   global.ajaxLoading.pop("文本下发成功!",true,1000);
	                	   }else if(item.replyCode=="34817"&&item.uuid==data.uuid){
	                		   if(item.imageUrl){
	                			   global.ajaxLoading.pop("拍照成功!",true,1000); 
	                			   $("#photo").attr("src",item.imageUrl);
	                			   if(index.vehicleID==data.vehicleId){
	                				   var img = document.getElementById('popimg');
		                		        img.setAttribute('src',item.imageUrl);
		                		        img.onload = function(){
		                		            var width = img.width,
		                		                height = img.height;
		                		            $('.lager-img').css({
		                		                width : width,
		                		                height: height,
		                		                'margin-top' : -height/2,
		                		                'margin-left' : -width/2
		                		            });
		                		        }; 
	                			   };
	                			   index.ImgUrlCache.put(data.vehicleId,item.imageUrl);
	                		   }else{
	                			   global.ajaxLoading.pop("拍照指令接收超时!",true,1000);
	                		   }  
	                	   }
	                   }else{     // 发送失败 处理
	                	   global.ajaxLoading.pop("接收指令回复超时!",true,1000);
	                   }
	                   $(".textarea-order").val("");
	               }
	         });
    	}
    },
    /**
     * 增加覆盖物
     * @param map
     * @param lon
     * @param lat
     */
	 addMarker : function(data){
		 data.vehicleId = data.vehicleId || data.id;
		if(data.carStatus == 1){
			data.status = '运行';
		}else if(data.carStatus == 2){
			data.status = '停车';
		}else{
			data.status = '掉线';
		}
		var picUrl = mapTool.getVehicleStatusPicUrl(data.head,data.carStatus);
		marker = new AMap.Marker({
	        map: mapTool.map,
	        position: [data.longitude, data.latitude],
	        icon: picUrl,
	        offset: new AMap.Pixel(-15, -10),
	        autoRotation: true
	    });
		marker.setLabel({//label默认蓝框白底左上角显示，样式className为：amap-marker-label
	        offset: new AMap.Pixel(20, 20),//修改label相对于maker的位置
	        content: data.vehicleNo
	    });
//		marker.content = '平台：'+index.PF_Name+'</br>业户：'+index.subName+'</br>车牌号：'+data.vehicleNo+'</br>速度：'+data.gpsSpeedF+' 公里/小时</br>里程：'+data.gpsMileage+'公里</br>定位时间：'+data.gpsTimeS+'</br>状态：'+data.status;
		marker.content = '车牌号：'+data.vehicleNo+'</br>速度：'+data.gpsSpeedF+' 公里/小时</br>里程：'+data.gpsMileage+'公里</br>定位时间：'+data.gpsTimeS+'</br>状态：'+data.status;
		if(index.infoWindow&&index.MARKID==data.vehicleId){
			index.infoWindow.on('close',function(){
				//index.infoWindow=null;
				index.MARKID = null;
			}); 
		}
		
		marker.on('click', function(e){
			index.infoWindow = new AMap.InfoWindow({offset: new AMap.Pixel(0, 0)});
			index.isopenWin=true;
			index.vehicleID = data.vehicleId;
			var item = index.GlobelVehicle.get(data.vehicleId);
			index.loadBaseInfo(item,'grid',data);
			index.detailInit.clickCar(0);
			index.MARKID=data.vehicleId;
			index.infoWindow.setContent(e.target.content);
			index.infoWindow.open(mapTool.map, e.target.getPosition());
			setTimeout(function(){
				index.MARKID=data.vehicleId;
			},500);
			//idnex.queryDriverInfo(item.noColor);
		});
		if(index.infoWindow&&index.MARKID==data.vehicleId){
			var mark = mapTool.initHashMap.GlobalMarkerCache.get(index.MARKID);
			//mark.content = '车牌号：'+data.vehicleNo+'</br>速度：'+data.gpsSpeedF+' 公里/小时</br>里程：'+data.gpsMileageF+'公里</br>定位时间：'+data.gpsTimeStr+'</br>状态：'+data.status;
			//index.infoWindow.setContent(mark.content);
			index.infoWindow.setContent(marker.content);
			index.infoWindow.open(mapTool.map,[data.longitude, data.latitude]);
			/*var item = index.GlobelVehicle.get(index.MARKID);
			index.loadBaseInfo(item);*/
		};
		mapTool.initHashMap.GlobalMarkerCache.put(data.vehicleId,marker);
	},
	/**
	 * 订阅全部取消
	 */
	cancelAll : function(){
		index.myGrid.clearAll();
		index.GlobalGpsCache.clear();
		index.arrayObj = new Array();
		mapTool.clearAllMarker();
		clearInterval(index.vehicleArrayTimer); 
		$("#cancel").css("display","none");
		index.carTree.checkAllNodes(false);
		/*var checks = $("#vehicleSeachTable").getCheckedRows();
		for(var i=0;i<checks.length;i++){
			$("#ck_"+checks[i]).removeAttr("checked");
		}*/
		$('.result').find('input[type=checkbox]').removeAttr("checked");
		index.vehicleStatus=[0,0,0,0];		
		$(".all-num").text(index.vehicleStatus[0]);
		$(".run-num").text(index.vehicleStatus[1]);
		$(".stop-num").text(index.vehicleStatus[2]);
		$(".dropped-num").text(index.vehicleStatus[3]);
		if(index.MARKID){
			index.MARKID=null;
			index.infoWindow.close();
		}
	},
	/**
	 * 加载订阅表格
	 */
	reloadGridData : function(data){
		 var getAddressCallback = function(address,jsonData){
	    	 if(jsonData == null || !jsonData.hasOwnProperty("vehicleId") ) return;
	    		jsonData.address = address;
	    		var gpsJson = index.GlobalGpsCache.get(jsonData.vehicleId);
	    		if(gpsJson != null){
	    			gpsJson.data[index.GlobalGridField.indexOf("address")] = address;
	    			index.GlobalGpsCache.put(jsonData.vehicleId,gpsJson);
	    		}
	    		if(index.GlobalGridField.indexOf("address")>0){
//	    			index.reloadGridData();
	    			index.myGrid.cells(jsonData.vehicleId,index.GlobalGridField.indexOf("address")).setValue(address);
	    		}   		
	    		//{resTime:解析时间（毫秒表示）,address:解析的地址}
	    		//var obj = {resTime:new Date().getTime(),address:address};
	    		index.GlobalAddress.put(jsonData.vehicleId,address);
	     }
		index.myGrid.clearAll();
		if(!data){
			data = {
				rows:index.GlobalGpsCache.values()
			};
		}
		index.myGrid.parse(data,"json");
		var entitys = data.rows;
		for(var i=0;i<entitys.length;i++){
			var jsonData = index.GlobelSubScribeVehicle.get(entitys[i].id);
			mapTool.getAddressExtend(null,jsonData,getAddressCallback);
		}		 
	},
    bind : function(){
		var _this = this;
		var mapW = $('#mymap').width();
		//地图全屏
		$('#mapAllLi').click(function(){
			if($(this).hasClass('active')){
				$(this).removeClass('active');
				$('.content').css({
					'margin-left':'300px'
				});
				$('#mymap').css({
					width:mapW,
					height:_this.mapH
				});
				$('.header,.slider,.monitor-detail,.car-staues,#nResizeDiv').show();
			}else{
				$(this).addClass('active');
				$('.content').css({
					'margin-left':0
				});
				$('#mymap').css({
					width:$('body').width(),
					height:$('body').height()
				});
				$('.header,.slider,.monitor-detail,.car-staues,#nResizeDiv').hide();
			}
			
		});
		
        //显示更多车辆详情
        $('.car-btn-hide').click(function(){
            if($(this).hasClass('active')){
                $(this).removeClass('active');
                $('.detail-more').hide();
            }else{
                $(this).addClass('active');
                $('.detail-more').show();
            }
        });

        //隐藏更多车辆详情
        $('.close-detail-more').click(function(){
            $('.car-btn-hide').removeClass('active');
            $('.detail-more').hide();
        });

        /*$('.look-bigimg').click(function(){
            _this.lookBigImg();
        });

        $('.lager-img').find('.close-pop').click(function(){
            $('.lager-img').hide();
            $('#mask').hide();
        });*/
        
        var searchFunc = function(){
        	var sarchVal = $.trim($('.search-input').val());
        	if(sarchVal){
        		_this.searchTable();
        	}else{
        		global.ajaxLoading.pop("请输入查询关键字",false,1000);
        	}      	
        	_this.treeTabInit.searchFunc(1);
        };
        
        $('.search-btn').click(function(){
        	if($('.tree-cont .result').is(':hidden')){
        		var sarchVal = $.trim($('.search-input').val());
        		if(sarchVal == ''){
        			$('#carTreeList').show();
            		$("#searchCarTree").hide();
        		}else{
        			_this.searchTreeInit.search(sarchVal);
        		}
        	}else{
        		searchFunc();
        	}
        });
        
        document.onkeydown=function(event){
            if(event.keyCode == 13){
            	if($('.tree-cont .result').is(':hidden')){
            		
            	}else{
            		searchFunc();
            	}
            }
        }
        
        $('.export').find('.icon-export').click(function(){	
        	index.exportExcel();
        });
        
        $('.export').find('.icon-cancel').click(function(){	
        	index.cancelAll();
        });
        
        /*$('.car-track').click(function(){
        	if(index.vehicleID){
        		if(index.GlobelVehicle.get(index.vehicleID).isPublicNet>0){
        			 var url = appCtx+"video/hisVideo.html?vehicleID="+index.vehicleID;
               		 window.open(url,"_blank");
        		}else{
        			global.ajaxLoading.pop("所选车辆不支持视频",false,1000);
        		}   		
        	}else{
        		global.ajaxLoading.pop("请选择车辆",false,1000);
        	}
   		
        });*/
        
        /*$('.car-trackplay').click(function(){
        	if(index.vehicleID){
        		var noColor = index.base64.encode(index.vehicleNoColor.get(index.vehicleID));
        		var url = appCtx+"gis/playback/trackPlayBack.html?vehicle_no_color="+noColor;
          		window.open(url,"_blank");	
        	}else{
        		global.ajaxLoading.pop("请选择车辆",false,1000);
        	}
        });*/
	
		 $('.playbackurl').click(function(){
			 if(index.vehicleID){
				 var noColor = index.base64.encode(index.vehicleNoColor.get(index.vehicleID));
		   		 var url = appCtx+"gis/playback/trackPlayBack.html?vehicle_no_color="+noColor;
		   		 window.open(url,"_blank");
			 }else{
				 global.ajaxLoading.pop("请选择车辆",false,1000);
			 };
			 $('.close-detail-more').click();
        });     
		 $('.monitorurl').click(function(){
			 if(index.vehicleID){
				 var noColor = index.base64.encode(index.vehicleNoColor.get(index.vehicleID));
		   		 var url = appCtx+"gis/monitor/multiVehicleMonitor.html?vehicle_no_color="+noColor;
		   		 window.open(url,"_blank");
			 }else{
				 global.ajaxLoading.pop("请选择车辆",false,1000);
			 };
			 $('.close-detail-more').click();
        }); 
		$('.multivideourl').click(function(){
			 if(index.vehicleID){
				 var noColor = index.base64.encode(index.vehicleNoColor.get(index.vehicleID));
		   		 var url = appCtx+"video/videoMonitorMT.html?vehicle_no_color="+noColor;
		   		 window.open(url,"_blank");
			 }else{
				 global.ajaxLoading.pop("请选择车辆",false,1000);
			 };
			 $('.close-detail-more').click();
        }); 
		 /*$('.car-video').click(function(){
			 if(index.vehicleID){
				 if(index.GlobelVehicle.get(index.vehicleID).isPublicNet>0){
					 var noColor = index.base64.encode(index.vehicleNoColor.get(index.vehicleID));
					 var url = appCtx+"video/videoMonitor.html?vehicle_no_color="+noColor;
	        		 window.open(url,"_blank");
				 }else{
					 global.ajaxLoading.pop("所选车辆不支持视频",false,1000); 
				 }			  
			 }else{
				 global.ajaxLoading.pop("请选择车辆",false,1000);
			 }   		
         }); */
		 $('.videourl').click(function(){
			 if(index.vehicleID){
				 if(index.GlobelVehicle.get(index.vehicleID).isPublicNet>0){
					 var noColor = index.base64.encode(index.vehicleNoColor.get(index.vehicleID));
					 var url = appCtx+"video/videoMonitor.html?vehicle_no_color="+noColor;
	        		 window.open(url,"_blank"); 
				 }else{
					 global.ajaxLoading.pop("所选车辆不支持视频",false,1000);
				 }			 
			 }else{
				 global.ajaxLoading.pop("请选择车辆",false,1000);
			 };
			 $('.close-detail-more').click();
         });
		 
		 $("#listMap").click(function(){
			 var url = appCtx+"gis/matter/logisticsMap.html";
    		 window.open(url,"_blank"); 
		 });
		 
		 $("#mTrafficLi").toggle(function(){
			 index.trafficLayer = new AMap.TileLayer.Traffic({zIndex:10}); //实时路况图层
			 index.trafficLayer.setMap(mapTool.map);
			 $('.t8').addClass("active");
		 },function(){
			 index.trafficLayer.setMap(null);
			 $('.t8').removeClass("active");
		 });
		 
		 $("#distanceLi").click(function(){
			  mapTool.map.plugin(["AMap.RangingTool"], function() {
			     ruler = new AMap.RangingTool(mapTool.map);
		         AMap.event.addListener(ruler, "end", function(e) {
		            ruler.turnOff();
		            $('.t6').removeClass("active");
		         });
		         ruler.turnOn();
		         $('.t6').addClass("active");
			  });
		 });
		 
		 $("#showMap").toggle(function(){  //展示地物点
			 $('.t13').addClass("active");
			 index.customPointShow();
//			 index.customLineShow();
//			 index.customMapShow();
		 },function(){     //关闭地物点
			 $('.t13').removeClass("active");
			// $('.t13').css("background-color","rgb(255, 255, 255)");
			 mapTool.map.remove(index.GlobalMarkerMatterCache);
			 index.GlobalMarkerMatterCache=[];
		 });
		 
		 //显示分享车辆窗口
		 /*$(".shareVehicleurl").click(function(){
			$("#vehicleShareurl_text").text("");
			var vehicleId=index.vehicleID;
			if(vehicleId){
				$("#shareVehicleId").val(vehicleId);
				$("#vehicleShareModal").modal("show");
			}else{
				global.ajaxLoading.pop("请选择车辆",false,1000);
			}	
			$('.close-detail-more').click();
		 });
		 //获取分享车辆url
		 $("#saveVehicleShareDateBtn").click(function(){
			 if(index.vehicleID){
				 index.saveVehicleShareDate();
			 }else{
				 global.ajaxLoading.pop("请选择车辆",false,1000);
			 }	 
	     });*/
		 
		 /*
		  * 左边定位树显示隐藏
		  */
		 $('#hideTree').click(function(){
			 var initWidthps = '11,11,5,5,12,5,5.5,5.5,19,20';
			 var initWidths = '120,120,50,50,125,50,60,60,200,210';
			 if($(this).hasClass('active')){
				 $(this).removeClass('active');
				 $('.slider').animate({'left':0},300);
				 $('.content').animate({'margin-left':'300px'},300,function(){
					 //index.myGrid.setInitWidths(initWidthps);
					 index.myGrid.setColWidth(9,210);
					 index.myGrid.setSizes();
				 });
				 
			 }else{
				 $(this).addClass('active');
				 $('.slider').animate({'left':'-300px'},300);
				 $('.content').animate({'margin-left':0},300,function(){
					 //index.myGrid.setInitWidthsP(initWidthps);
					 //index.myGrid.setInitWidths('120,120,50,50,125,50,60,60,200,510');
					 index.myGrid.setColWidth(9,510);
					 index.myGrid.setSizes();
				 });
			 }
		 });
		 
		 $("#copyVehicleUrlBtn").click(function(){
	    		var value = $("#vehicleShareurl_text").text();
	    		if(value){
	    			_this.copy();
	    		}else{
	    			 global.ajaxLoading.pop("无分享的链接复制！",true,1000);
	    		}
	    }); 
     },
     copy : function(){
 		var c1 = new ClipBoard({
 		    handlerID: 'copyVehicleUrlBtn',
 		    textID: 'vehicleShareurl_text',
 		    isAttr: false,
 		    type:'copy'
 		});
 		c1.attach(); // 触发复制/剪切功能
 	},
     saveVehicleShareDate:function(){
    	var base = new Base64();
    	var inputDate=$("#inputDate").val().replace(/\-/g,"\/");
    	var action = $("#action").val();
    	var decodeKey = new Date(inputDate).getTime();
    	var encodeKey = base.encode(decodeKey.toString());
    	if(inputDate==""){
    		global.ajaxLoading.pop("请设置期限！",false,1000);
    		return ;
    	}
    	var now = new Date().getTime();
    	if(decodeKey<now&&action=="share"){
    		global.ajaxLoading.pop("期限不能小于当前时间！",false,1000);
    		return ;
    	}
    	if(decodeKey<now&&action=="update"){
    		global.ajaxLoading.pop("期限不能小于当前时间！",flase,1000);
    		return ;
    	}
    	var vehicleId=$("#shareVehicleId").val();
    	var action="share";
    	$.ajax({
	    	type : 'post',
	    	async : false,
	    	url : appCtx + "system/vehicle/saveVehicleShareDate.html?vehicleId="+index.vehicleID+"&shareKey="+encodeKey+"&path="+appCtx+"&action="+action,
	    	cache : false,
	    	dataType : "JSON",
	    	success : function(data) {			
	    		if(data){
	    			if(data.msg!="成功"){
	    				global.ajaxLoading.pop(data.msg,flase,1000);
	    				var val = $("#saveVehicleShareDateBtn").val();
	    			}else{
	    				global.ajaxLoading.pop("操作成功！",true,1000);
		    			var url=appCtx+"system/vehicle/shareVehicle.html?shareKey="+encodeKey+"&vehicleId="+index.vehicleID;
		    			$("#vehicleShareurl_text").html(url);
			    		$("#vehicleShareurl_text").show();
			    		var val = $("#saveVehicleShareDateBtn").val();
	    			}	    			
	    		}  		
	    	}	
	    });	  
    },
	customMapShow:function(){
		_this=this;
		$.ajax({
			type : 'post',
			async : true,
			url :  appCtx + "/gis/matter/queryCustomMapList.html",
			cache : false,
			dataType : "json",
			success : function(data) {
				 if(data.data!=null && data.data.length>0){
					 for(var i=0;i<data.data.length;i++){
						 obj=data.data[i];
						 var point = new AMap.LngLat(obj.lon,obj.lat);
							var iconUrl= appCtx + 'resources/images/mapTool/home_icon_location.png';
							var content = '名称：'+obj.name+'</br>类型：'+formatMapTypeAction(obj.maplayerid)+'</br>所属企业：'+obj.workunitName+'</br>位置：'+obj.address+'</br>备注：'+obj.remark;
							var polygonArr = new Array();//多边形覆盖物节点坐标数组
							var lnglatAry =   (obj.lonlat).split(",");
							for(var i=0;i<lnglatAry.length;i++){
								var  lonlat = lnglatAry[i].split("|"); 
								var lng  = lonlat[0];
								var lat  = lonlat[1]; 
								polygonArr.push([lng,lat]);
							}
					       if(obj.drawingType=="circle"){ // 圆形
					    	 var  radius = obj.radius!=""?parseFloat(obj.radius):1;
					    	 var circle = new AMap.Circle({
					 	        center: point,// 圆心位置
					 	        radius: radius, //半径
					 	        strokeColor: "blue", //线颜色
					 	        strokeOpacity: 1, //线透明度
					 	        strokeWeight: 3 , //线粗细度
					 	        fillColor: "#ee2200", //填充颜色
					 	        fillOpacity: 0//填充透明度
					 	    });
					 	    circle.setMap(mapTool.map);
						 	    index.GlobalMarkerMatterCache.push(circle);
					       }else{ // 多边形 或矩形
					    	    var  polygon = new AMap.Polygon({
					    	        path: polygonArr,//设置多边形边界路径
					    	        strokeColor: "#FF33FF", //线颜色
					    	        strokeOpacity: 0.2, //线透明度
					    	        strokeWeight: 3,    //线宽
					    	        fillColor: "#1791fc", //填充色
					    	        fillOpacity: 0.35//填充透明度
					    	    });
					    	    polygon.setMap(mapTool.map);
						    	index.GlobalMarkerMatterCache.push(polygon);
					       }
						   _this.addMatterMarker(obj.lon,obj.lat,content,iconUrl);
					 }
				 }
			}
		});
	},
	customPointShow:function(){
		_this=this;
		$.ajax({
			type : 'post',
			async : true,
			url :  appCtx + "/gis/matter/queryCustomMapPointList.html",
			cache : false,
			dataType : "json",
			success : function(data) {
				 if(data.data!=null && data.data.length>0){
					 for(var i=0;i<data.data.length;i++){
						 obj=data.data[i];
						 var point = new AMap.LngLat(obj.lon,obj.lat);
							var iconUrl= appCtx + 'resources/images/mapTool/home_icon_location.png';
							var content = '名称：'+obj.name+'</br>类型：'+formatMapTypeAction(obj.maptype);
							if(obj.radius>0){
								var circle = new AMap.Circle({
							        center: point,// 圆心位置
							        radius: obj.radius, //半径
							        strokeColor: "blue", //线颜色
							        strokeOpacity: 1, //线透明度
							        strokeWeight: 3 , //线粗细度
							        fillColor: "#ee2200", //填充颜色
							        fillOpacity: 0//填充透明度
							    });
							    circle.setMap(mapTool.map);
							    index.GlobalMarkerMatterCache.push(circle);
							}
							_this.addMatterMarker(obj.lon,obj.lat,content,iconUrl);
					 }
				 }
			}
		});
	},
	customLineShow:function(){
		_this=this;
		$.ajax({
			type : 'post',
			async : true,
			url :  appCtx + "/gis/matter/queryCustomLineList.html",
			cache : false,
			dataType : "json",
			success : function(data) {
				for(var i=0;i<data.data.length;i++){
					 obj=data.data[i];
					 var point = new AMap.LngLat(obj.qdlongitude,obj.qdlatitude);
					 var iconUrl= appCtx+"resources/images/mapTool/p_start.png";//"http://webapi.amap.com/theme/v1.3/markers/n/mark_b.png" ;
						var iconUrlz= appCtx+"resources/images/mapTool/p_end.png" ; //"http://webapi.amap.com/theme/v1.3/markers/n/mark_r.png" ;
						var content = '名称：'+obj.name+'</br>所属企业：'+obj.workunitName+'</br>起点：'+obj.startPoint+'</br>里程：'+obj.mileage+'</br>备注：'+obj.remark;
						var contentz = '名称：'+obj.name+'</br>所属企业：'+obj.workunitName+'</br>终点：'+obj.endPoint+'</br>里程：'+obj.mileage+'</br>备注：'+obj.remark;
						// 取得线路中的点
						$.ajax({
							type : 'post',
							async : true,
							data :[{name : 'lineID',value :obj.id}],
							url :  appCtx + "/gis/matter/queryAllCustomLinePointById.html",
							cache : false,
							dataType : "json",
							success : function(data) {
								 if(data.data!=null && data.data.length>0){
									 var polylinePointsArray = [];
									 for(var i=0;i<data.data.length;i++){// 线路
										 polylinePointsArray.push([data.data[i].longitude,data.data[i].latitude]);
							     	 }
									 var polyline = new AMap.Polyline({
									        path: polylinePointsArray,          //设置线覆盖物路径
									        strokeColor: "#3366FF", //线颜色
									        strokeOpacity: 1,       //线透明度
									        strokeWeight: 5,        //线宽
									        strokeStyle: "solid",   //线样式
									        strokeDasharray: [10, 5] //补充线样式
									    });
									    polyline.setMap(mapTool.map);
									    index.GlobalMarkerMatterCache.push(polyline);
								 }
							}
						});
						_this.addMatterMarker(obj.qdlongitude,obj.qdlatitude,content,iconUrl);
						_this.addMatterMarker(obj.zdlongitude,obj.zdlatitude,contentz,iconUrlz);
				}
			}
		});
	},addMatterMarker:function(longitude,latitude,content,iconUrl){
		var infoWindow = new AMap.InfoWindow({offset: new AMap.Pixel(0, -30)}); 
		var marker = new AMap.Marker({
	       position: [longitude,latitude],
	       icon: iconUrl
		});
		marker.setMap(mapTool.map);
		marker.content =content;
		marker.on('click', function(e){
			 infoWindow.setContent(e.target.content);
		     infoWindow.open(mapTool.map, e.target.getPosition());
		});

		index.GlobalMarkerMatterCache.push(marker);

	},
	
	queryDriverInfo: function(params){
		$.ajax({
			type : 'get',
			data :{'vehicle_no_color':params},
			url :  appCtx + "gis/monitor/queryDriverInfo.html",
			dataType : "json",
			success: function(data){
				if(data){
					var hours = data.totalDriverTime % 3600 / 1000;
					var hour = (data.totalDriverTime - hours) / 3600 / 1000;
					var monit = (data.totalDriverTime - hour * 3600) % 60 / 1000;
					var totalDriverTime =hour + '小时' + monit + '分';
					var tired = data.tired ? '是' : '否';
					var $cardetails = $('.car-details');
					$cardetails.find('.driverName').html(data.driverName);
					$cardetails.find('.totalDriverTime').html(totalDriverTime);
					$cardetails.find('.tired').html(tired);
					$cardetails.find('.max_speed').html(data.max_speed + 'km/h');
					$cardetails.find('.overspeed_count').html(data.overspeed_count);
					if(data.imgUrl){
						$cardetails.find('.imgUrl').find('img').attr('src',data.imgUrl);
					}else{
						$cardetails.find('.imgUrl').find('img').attr('src',appCtx+'resources/images/touxiang.jpg');
					}
				}
			}
		});
	},
	/**
     * 点击列表的时候时候改变覆盖物(车辆)的大小
     * @param map
     * @param lon
     * @param lat
     */    
	 addMarkerForClick : function(data){
		
		if(data.vehicleId == index.vehicleIdIndex){
			
		}else{
            $('#monitorSize').hide();
		}
		 //关闭上一个窗口
		if(index.MARKID){
			index.MARKID=null;
			index.infoWindow.close();
		}
		var contenttext =
			'车牌号：'+data.vehicleNo
			+'</br>速度：'+data.gpsSpeedF
			+' 公里/小时</br>里程：'+data.gpsMileageF
			+'公里</br>定位时间：'+data.gpsTimeStr
			+'</br>状态：'+data.status;
		//index.showAddress(data.vehicleId,data.longitude,data.latitude,contenttext,null);
		index.infoWindow = new AMap.InfoWindow({offset: new AMap.Pixel(0, 0)});		
		index.isopenWin=true;
		var item = index.GlobelVehicle.get(data.vehicleId);
		index.detailInit.clickCar(0);
		//删除选中覆盖物
		mapTool.clearMarker(data.vehicleId);
		//并且上一个车依然还被订阅
		if(index.lastData!=null){
			if(data.vehicleId != index.lastData.vehicleId){
				mapTool.clearMarker(index.lastData.vehicleId);//删除上一个覆盖物
				//测试
				var picUrl = mapTool.getVehicleStatusPicUrl(index.lastData.head,index.lastData.carStatus);		
				var marker = new AMap.Marker({
			        map: mapTool.map,
			        position: [index.lastData.longitude, index.lastData.latitude],
			        icon: picUrl,
			        offset: new AMap.Pixel(-15, -10),
			        autoRotation: true
			    });
				var lastData = index.lastData;
				marker.content = '车牌号：'+lastData.vehicleNo+'</br>速度：'+lastData.gpsSpeedF+' 公里/小时</br>里程：'+lastData.gpsMileageF+'公里</br>定位时间：'+lastData.gpsTimeStr+'</br>状态：'+lastData.status;
				var contenttext =
					'车牌号：'+lastData.vehicleNo
					+'</br>速度：'+lastData.gpsSpeedF
					+' 公里/小时</br>里程：'+lastData.gpsMileageF
					+'公里</br>定位时间：'+lastData.gpsTimeStr
					+'</br>状态：'+lastData.status;
				mapTool.initHashMap.GlobalMarkerCache.put(index.lastData.vehicleId,marker);
				//设置上面的标签
				marker.setLabel({//label默认蓝框白底左上角显示，样式className为：amap-marker-label
			        offset: new AMap.Pixel(20, 20),//修改label相对于maker的位置
			        content: index.lastData.vehicleNo
			    });
				marker.on('click', function(e){

					//index.showAddress(lastData.vehicleId,lastData.longitude,lastData.latitude,contenttext,null);
					index.infoWindow = new AMap.InfoWindow({offset: new AMap.Pixel(0, 0)});
					index.isopenWin=true;
					var item = index.GlobelVehicle.get(data.vehicleId);
					//index.loadBaseInfo(item,'grid',data);
					index.detailInit.clickCar(0);
					index.MARKID=data.vehicleId;
					index.infoWindow.setContent(e.target.content);
					index.infoWindow.open(mapTool.map, e.target.getPosition());
								
					setTimeout(function(){
						index.MARKID=lastData.vehicleId;
					},500);
					
					//给打开的窗口绑定关闭事件
					if(index.infoWindow&&index.MARKID==lastData.vehicleId){
						index.infoWindow.on('close',function(){
							//index.infoWindow=null;
							index.MARKID = null;
						}); 
					}
				});
			}
		}
		//判断给车什么颜色
		 var color = data.carStatus;
		 var bigCar=null;
		 if(color==1){
			bigCar=5;//蓝色大图标
		 }
		 if(color==2){
			 bigCar=6;//黄色大图标
		 }
		 if(color==3){
			 bigCar=7;//灰色大图标
		 }
		 if(color==4){
			 bigCar=8;//红色大图标
		 }				
		var picUrl = mapTool.getVehicleStatusPicUrl(data.head,bigCar);		
		marker = new AMap.Marker({
	        map: mapTool.map,
	        position: [data.longitude, data.latitude],
	        icon: picUrl,
	        offset: new AMap.Pixel(-23, -20),
	        //offset: new AMap.Pixel(-15, -10),
	        autoRotation: true
	    });
		//设置上面的标签
		marker.setLabel({//label默认蓝框白底左上角显示，样式className为：amap-marker-label
	        offset: new AMap.Pixel(20, 20),//修改label相对于maker的位置
	        content: data.vehicleNo
	    });
		index.lastData=data;
		mapTool.initHashMap.GlobalMarkerCache.put(data.vehicleId,marker);
		marker.on('click', function(e){
			index.MARKID=data.vehicleId;//打开详细窗口控制器
			if(index.infoWindow&&index.MARKID==data.vehicleId){
				var mark = mapTool.initHashMap.GlobalMarkerCache.get(index.MARKID);
				mark.content = '车牌号：'+data.vehicleNo+'</br>速度：'+data.gpsSpeedF+' 公里/小时</br>里程：'+data.gpsMileageF+'公里</br>定位时间：'+data.gpsTimeStr+'</br>状态：'+data.status;
				var contenttext =
					'车牌号：'+data.vehicleNo
					+'</br>速度：'+data.gpsSpeedF
					+' 公里/小时</br>里程：'+data.gpsMileageF
					+'公里</br>定位时间：'+data.gpsTimeStr
					+'</br>状态：'+data.status;
				//index.showAddress(data.vehicleId,data.longitude,data.latitude,contenttext,null);//新添加 hkj
				//mark.content = '车牌号：'+data.vehicleNo+'</br>速度：'+data.gpsSpeedF+' 公里/小时</br>里程：'+data.gpsMileageF+'公里</br>定位时间：'+data.gpsTimeStr+'</br>状态：'+data.status;
				index.infoWindow.setContent(marker.content);
				index.infoWindow.open(mapTool.map,[data.longitude, data.latitude]);
			};
			//给新建的窗口绑定关闭事件
			if(index.infoWindow&&index.MARKID==data.vehicleId){
				index.infoWindow.on('close',function(){
					//index.infoWindow=null;
					index.MARKID = null;
				}); 
			}
		});
			
		setTimeout(function(){
			//index.MARKID=data.vehicleId;
		},500);
		
		mapTool.initHashMap.GlobalMarkerCache.put(data.vehicleId,marker);
	}
};

index.init();
function showVideo(vehicleId){
 	var url = appCtx+"video/videoMonitor.html?vehicleID="+vehicleId;
 	window.open(url,"_blank"); 
};
function showTrack(vehicleId){
	var url = appCtx+"gis/playback/trackPlayBack.html?vehicle_no_color="+vehicleId;
	window.open(url,"_blank");
};
function cancelTrack(vehicleId){
	if(index.loadBaseInfoId == vehicleId){
		index.resetDetail();
		if(index.infoWindow){
			index.infoWindow.close();
		}
	}
	//var vehileNode = index.carTree.getNodesByParam("VID", vehicleId, null);
	/*index.carTree.checkNode(vehileNode[0], false, true);*/
	//global.arr.removeElm(index.arrayObj,index.terminalMap.get(vehileNode[0].VID));
	var vehicleNoColor = index.vehicleNoColor.get(vehicleId);
	global.arr.removeElm(index.arrayObj,vehicleNoColor);
	mapTool.clearMarker(vehicleId);
	index.myGrid.deleteRow(vehicleNoColor);
	index.GlobalGpsCache.remove(vehicleId);
	$("#"+vehicleId).find('input').removeAttr("checked");
	//$('#' + vehicleId).find('input').checked = false;
	index.vehicleStatus[0]--;
	if(index.GlobelSubScribeVehicle.get(vehicleId)){
		var carStatus = index.GlobelSubScribeVehicle.get(vehicleId).carStatus;
		if(carStatus==1){
			index.vehicleStatus[1]--;
		}else if(carStatus==2){
			index.vehicleStatus[2]--;
		}else if(carStatus==3){
			index.vehicleStatus[3]--;
		}
	}	
	if(index.arrayObj.length>0){
		index.subScribe(index.arrayObj.toString());
	}else{
		clearInterval(index.vehicleArrayTimer);
		index.GlobalGpsCache.clear();
		index.myGrid.clearAll();
		index.vehicleStatus=[0,0,0,0];
		if(index.MARKID){
			index.MARKID=null;
			index.infoWindow.close();
		}
	}
	$(".all-num").text(index.vehicleStatus[0]);
	$(".run-num").text(index.vehicleStatus[1]);
	$(".stop-num").text(index.vehicleStatus[2]);
	$(".dropped-num").text(index.vehicleStatus[3]);	
}

//自定义列
function eXcell_cancelBtn(cell){
	if(cell){
		this.cell = cell;
		this.grid = this.cell.parentNode.grid;
	}
	this.edit = function(){}
	this.isDisable = function(){return true;}
	this.setValue = function(val){
		var vehicleId = val;
		var handleStr = "";	
		var vehicle_no_color = index.base64.encode(index.vehicleNoColor.get(vehicleId));
		if(index.GlobelVehicle.get(vehicleId)!=null&&index.GlobelVehicle.get(vehicleId).isPublicNet>0){
			handleStr = '<div style="padding:0px;float:left;width:33%;height:19px;cursor:pointer;text-align:center;">'+
								'<img src="'+global.url.domain+'gps-web/resources/images/cancelSub.png" title="取消" onclick="cancelTrack('+vehicleId+')" />'+
							'</div>'+
							'<div style="padding:0px;float:left;width:33%;height:19px;cursor:pointer;text-align:center;">'+
								'<a href="'+appCtx+'video/videoMonitor.html?vehicle_no_color='+vehicle_no_color+'" target="_blank"><img src="'+global.url.domain+'gps-web/resources/images/video.png" title="视频监控" onclick="showVideo('+vehicleId+')" /></a>'+
							'</div>'+
							'<div style="padding:0px;float:left;width:33%;height:19px;cursor:pointer;text-align:center;">'+
								'<a href="'+appCtx+'gis/playback/trackPlayBack.html?vehicle_no_color='+vehicle_no_color+'" target="_blank"><img src="'+global.url.domain+'gps-web/resources/images/track.png" title="轨迹回放" /></a>'+
							'</div>'; 				
		}else{
			handleStr = '<div style="padding:0px;float:left;width:33%;height:19px;cursor:pointer;text-align:center;">'+
								'<img src="'+global.url.domain+'gps-web/resources/images/cancelSub.png" title="取消" onclick="cancelTrack('+vehicleId+')" />'+
							'</div>'+
							'<div style="padding:0px;float:left;width:33%;height:19px;cursor:pointer;text-align:center;">'+
							'<a href="'+appCtx+'gis/playback/trackPlayBack.html?vehicle_no_color='+vehicle_no_color+'" target="_blank"><img src="'+global.url.domain+'gps-web/resources/images/track.png" title="轨迹回放" /></a>'+
							'</div>';
		}	
		this.setCValue(handleStr, val);
	}
}
eXcell_cancelBtn.prototype = new eXcell;

//订阅列表
function eXcell_TrackingBtn(cell){
	if(cell){
		this.cell = cell;
		this.grid = this.cell.parentNode.grid;
	}
	this.edit = function(){}
	this.isDisable = function(){return true;}
	this.setValue = function(val){
		var noColor = index.vehicleNoColor.get(val);
		if(noColor==null){
			this.setCValue('<a href="'+appCtx+'gis/monitor/vehicleMonitor.html" target="_blank" style="color:blue;"></a>' );
		}else{
			var vehicleNoColor = noColor.split('_');
			//var noColor = val + '_' + index.vehicleColor.get(val);
			var str = index.base64.encode(noColor);
			//str = b.decode(str);
			this.setCValue('<a href="'+appCtx+'gis/monitor/vehicleMonitor.html?vehicle_no_color='+str+'" target="_blank" style="color:blue;">'+vehicleNoColor[0]+'</a>', vehicleNoColor[0]);
		}
		
	}
}
eXcell_TrackingBtn.prototype = new eXcell;  

function eXcell_carStatus(cell){
	if(cell){
		this.cell = cell;
		this.grid = this.cell.parentNode.grid;
	}
	this.edit = function(){}
	this.isDisable = function(){return true;}
	this.setValue = function(val){
		var handleStr = '<div style="line-height:30px;margin-top:6px;"><div class="dn">'+val+'</div><div class="staues-icon all-icon" style="padding:0;margin:0 auto;width:8px;height:8px;"></div></div>';
		if(val == 1){
			val = "运行";
			handleStr = '<div style="line-height:30px;margin-top:6px;"><div class="dn">'+val+'</div><div class="staues-icon run-icon" style="padding:0;margin:0 auto;width:8px;height:8px;"></div></div>';
		}else if(val == 2){
			val = "停车";
			handleStr = '<div style="line-height:30px;margin-top:6px;"><div class="dn">'+val+'</div><div class="staues-icon stop-icon" style="padding:0;margin:0 auto;width:8px;height:8px;"></div></div>';
		}else if(val == 3){
			val = "掉线";
			handleStr = '<div style="line-height:30px;margin-top:6px;"><div class="dn">'+val+'</div><div class="staues-icon dropped-icon" style="padding:0;margin:0 auto;width:8px;height:8px;"></div></div>';
		}
		this.setCValue(handleStr, val);
	}
	
};
eXcell_carStatus.prototype = new eXcell;

/**
 * 格式化类型
 * */
function formatMapTypeAction (maptype)      
{   
	switch (parseInt(maptype)) {
	case 1:
		return "工厂";
	case 2:
		return "收费站";
	case 3:
		return "仓库";
	case 4:
		return "码头,堆场";
	case 5:
		return "物流园";
	case 6:
		return "其他";
	case 7:
		return "跟踪点";
	case 8:
		return "网点";
	case 9:
		return "政府";
	case 10:
		return "火车站";
	case 11:
		return "医院";
	default:
		return "网点";
	}
} 


